﻿using System;
using System.Data;
using System.Configuration;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./TruckerPrice.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 100;
    public string strPager = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    string strExcluded = "";
    public string strPartQuery = "";
    public string LocationInfo = "";
    protected float Distance = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;
        if (Session["logined_id"] != null)
        {
            if (Session["TruckerPrice"] != "") nPermissions = int.Parse(Session["TruckerPrice"].ToString());
            if (nPermissions <= 0) Response.Redirect("Login.aspx");
        }
        else
            Response.Redirect("Login.aspx");
        if (!Page.IsPostBack)
        {
            //strCondition = " AND ExID=" + Session["TruckerPriceExID"].ToString() + " AND ToID=" + Session["TruckerPriceToID"].ToString();
            if (Request.QueryString["pRoadID"] != null)
            {
                if (Request.QueryString["ExID"] != null && Request.QueryString["ToID"] != null)
                {
                    long lExID = 0;
                    long lToID = 0;
                    try
                    {
                        lExID = long.Parse(Request.QueryString["ExID"].ToString());
                    }
                    catch { }
                    try
                    {
                        lToID = long.Parse(Request.QueryString["ToID"].ToString());
                    }
                    catch { }
                    if (lExID > 0 && lToID > 0)
                    {
                        //Load EX
                        Huyen objH = new Huyen();
                        objH.ID = lExID;
                        objH.Load(GV.cn, GV.trans);
                        Session["TruckerPriceExID"] = objH.ID;
                        Session["Distance"] = objH.Kms;//Distance

                        Tinh objT = new Tinh();
                        objT.ID = objH.TinhID;
                        objT.Load(GV.cn, GV.trans);
                        Session["TruckerPriceEx"] = objH.Ten + ", " + objT.Ten;

                        //load To
                        Location objL = new Location();
                        objL.ID = lToID;
                        objL.Load(GV.cn, GV.trans);
                        Session["TruckerPriceToID"] = objL.ID;

                        LocationInfo = Session["TruckerPriceEx"].ToString() + " - " + objL.Name + " : " + objH.Kms + " km";

                    }
                }
            }
            if (Session["LocationInfo"] == null) Session["LocationInfo"] = "";
            if (Session["TruckerPriceEx"] != null) txtEX.Text = Session["TruckerPriceEx"].ToString();
            if (Session["Distance"] != null)
            {
                try
                {
                    Distance = float.Parse(Session["Distance"].ToString());
                }
                catch { }
            }
            LoadDropDownTo();
            btnInit.Visible = false;
            if (Request.QueryString["action"] == "delete" && nPermissions >= 9)
            {
                TruckerPrice obj = new TruckerPrice();
                obj.ID = long.Parse(Request.QueryString["ID"]);
                obj.Delete(GV.cn, GV.trans);
                UserObjectsLog.SaveObjectActionLog(long.Parse(Session["logined_id"].ToString()), "TruckerPrice", "Delete", GV.cn, GV.trans);
                Response.Redirect("TruckerPrice.aspx" + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "?page_number=" + Request.QueryString["page_number"].ToString() : ""));
            }
            if ((Session["TruckerPriceToID"] != null && int.Parse(Session["TruckerPriceToID"].ToString()) > 0)
                && (Session["TruckerPriceExID"] != null && int.Parse(Session["TruckerPriceExID"].ToString()) > 0))
            {
                strCondition = " AND ExID=" + Session["TruckerPriceExID"].ToString() + " AND ToID=" + Session["TruckerPriceToID"].ToString();
                int nRowCount = TruckerPrice.GetListCount(strCondition, GV.cn, GV.trans);
                if (nRowCount == 0)
                {
                    btnInit.Visible = true;
                }
                else
                    LoadBuildList();
            }
            //Pricing
            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToLower() == "pricing" && Request.QueryString["ID"] != null && Request.QueryString["pRoadID"] != null)
            {
                long lTrukerPriceID = 0;
                try
                {
                    lTrukerPriceID = long.Parse(Request.QueryString["ID"].ToString());
                }
                catch { }
                long lpRoadID = 0;
                try
                {
                    lpRoadID = long.Parse(Request.QueryString["pRoadID"].ToString());
                }
                catch { }
                if (lTrukerPriceID > 0 && lpRoadID > 0)
                {
                    //Load Trucker Price
                    TruckerPrice tk = new TruckerPrice();
                    tk.ID = lTrukerPriceID;
                    tk.Load(GV.cn, GV.trans);
                    //Load Pricing Road
                    PricingRoadForSales pr = new PricingRoadForSales();
                    pr.ID = lpRoadID;
                    pr.Load(GV.cn, GV.trans);
                    pr.Cont20 = tk.Cont20.Split('_')[0];
                    pr.Cont40 = tk.Cont40.Split('_')[0];
                    pr.TruckerID = tk.TruckerID;
                    pr.UserIDResponse = long.Parse(Session["logined_id"].ToString());
                    pr.Suare = 2;
                    pr.Save(GV.cn, GV.trans);
                    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
                }
            }
        }
    }
    private void LoadBuildList()
    {
        #region Build List
        int nNumOfPages = 0;

        DataTable dtList;
        BuildList(NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, GV.cn, GV.trans);
        if (nPage > nNumOfPages) nPage = 1;

        rptData.DataSource = dtList;
        rptData.DataBind();
        #endregion
        #region Build Pager
        CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
        #endregion
    }
    private void BuildList(int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("ID");
        dtList.Columns.Add("Index");
        dtList.Columns.Add("BizName");
        dtList.Columns.Add("Cont20");
        dtList.Columns.Add("VndKm20");
        dtList.Columns.Add("Tons20");
        dtList.Columns.Add("DoPrice20");
        dtList.Columns.Add("Note20");
        dtList.Columns.Add("Cont40");
        dtList.Columns.Add("VndKm40");
        dtList.Columns.Add("Tons40");
        dtList.Columns.Add("DoPrice40");
        dtList.Columns.Add("Note40");
        dtList.Columns.Add("Action");
        nNumOfPages = 0;
        if ((Session["TruckerPriceToID"] != null && int.Parse(Session["TruckerPriceToID"].ToString()) > 0)
               && (Session["TruckerPriceExID"] != null && int.Parse(Session["TruckerPriceExID"].ToString()) > 0))
        {
            strCondition = " AND ExID=" + Session["TruckerPriceExID"].ToString() + " AND ToID=" + Session["TruckerPriceToID"].ToString();
        }
        TruckerPrice.GetList(strCondition, " ID ASC", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";
        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            DataSet objds = null;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                objds = new DataSet();

                count++;
                string strID = dr["ID"].ToString();
                string strIndex = count.ToString();
                string BizName = dr["BizName"].ToString();
                string Cont20 = dr["Cont20"].ToString();
                string Tons20 = dr["Tons20"].ToString();
                string DoPrice20 = dr["DoPrice20"].ToString();
                string Note20 = dr["Note20"].ToString();
                string Cont40 = dr["Cont40"].ToString();
                string Tons40 = dr["Tons40"].ToString();
                string DoPrice40 = dr["DoPrice40"].ToString();
                string Note40 = dr["Note40"].ToString();
                string VndKm20 = "";
                float fvndKm20 = 0;
                string VndKm40 = "";
                float fvndKm40 = 0;
                if (Distance > 0)
                {
                    try
                    {
                        fvndKm20 = float.Parse(Cont20.Split('_')[0]) / Distance;
                    }
                    catch { }
                    try
                    {
                        fvndKm40 = float.Parse(Cont40.Split('_')[0]) / Distance;
                    }
                    catch { }
                    if (fvndKm20 > 0)
                    {
                        VndKm20 = fvndKm20.ToString("#,0.##");
                    }
                    if (fvndKm40 > 0)
                    {
                        VndKm40 = fvndKm40.ToString("#,0.##");
                    }
                }
                string strAction = "<div class=\"changed\">&nbsp;";
                //if (nPermissions > 7)
                //{
                //    strAction += " <a href=\"TruckerPrice.aspx?action=delete&ID=" + dr["ID"].ToString() + "\"> Delete </a>";
                //}
                DateTime dt20 = dr["LastUdate20"].ToString().Length > 0 ? DateTime.Parse(dr["LastUdate20"].ToString()) : DateTime.MinValue;
                DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                if (int.Parse(Session["PricingRoadForSales"].ToString()) > 1 && Request.QueryString["pRoadID"] != null && dt == dt20)
                {
                    strAction += " <a href=\"TruckerPrice.aspx?action=pricing&ID=" + dr["ID"].ToString() + "&pRoadID=" + Request.QueryString["pRoadID"].ToString() + "\"> Pricing </a>";
                }
                else
                {
                    strCondition += "&nbsp;";
                }
                strAction += "</div>";
                string[] strValues = new string[] { strID, strIndex,
                                    BizName,
                                    Cont20,
                                    VndKm20,
                                    Tons20,
                                    DoPrice20,
                                    Note20,
                                    Cont40,
                                    VndKm40,
                                    Tons40,
                                    DoPrice40,
                                    Note40,    
                                    strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    public string GetCellTitle(object inputstring)
    {
        string title = "";
        if (inputstring != null && !string.IsNullOrEmpty(inputstring.ToString()))
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate.Length > 1)
                title = arrUpdate[1];
        }
        return title;
    }
    public string GetCellClass(object inputstring)
    {
        string className = "";
        if (inputstring != null && !string.IsNullOrEmpty(inputstring.ToString()))
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate.Length > 1 && arrUpdate[0].Length > 0)
            {
                try
                {
                    string tempDt = arrUpdate[1].Substring(arrUpdate[1].Length - 10).Trim();
                    DateTime dt = DateTime.ParseExact(tempDt, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    if (dt.AddDays(7) >= DateTime.Now)
                        className = "has-value-lastweek";
                    else if (dt.AddDays(14) >= DateTime.Now && dt.AddDays(7) < DateTime.Now)
                        className = "has-value-last2week";
                    else
                        className = "has-value";
                }
                catch
                {
                    className = "";
                }
            }
        }
        return className;
    }
    public string GetCellClassVndKms(object inputstring)
    {
        string className = "";
        if (inputstring != null && !string.IsNullOrEmpty(inputstring.ToString()))
        {
            className = "has-value";
        }
        return className;
    }
    public string GetCellValue(object inputstring, bool emptyIfNull = false)
    {
        string cellvalue = !emptyIfNull ? "No check" : "";
        if (inputstring != null && inputstring.ToString().Trim().Length > 0)
        {
            string[] arrUpdate = inputstring.ToString().Split('_');
            if (arrUpdate[0].Length > 0)
            {
                cellvalue = arrUpdate[0];
                try
                {
                    cellvalue = double.Parse(cellvalue).ToString("#,0.##");
                }
                catch { }
            }
        }
        return cellvalue;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        lblerror.Text = "";
        Session["TruckerPriceToID"] = ddTO.SelectedValue.ToString();
        Session["TruckerPriceEx"] = txtEX.Text.Trim();
        Session["TruckerPriceExID"] = 0;
        if (Session["TruckerPriceEx"].ToString().Length > 0)
        {
            string DistricName = Session["TruckerPriceEx"].ToString().Split(',')[0];
            if (DistricName.Length > 0)
            {
                Huyen objHuyen = new Huyen();
                objHuyen.Load(DistricName, GV.cn, GV.trans);
                if (objHuyen.ID > 0)
                {
                    Session["TruckerPriceExID"] = objHuyen.ID;
                    LocationInfo = Session["TruckerPriceEx"].ToString() + " - " + ddTO.SelectedItem.Text;
                    Tinh objTinh = new Tinh();
                    objTinh.ID = objHuyen.TinhID;
                    objTinh.Load(GV.cn, GV.trans);

                    if (objTinh.VungID == long.Parse(ddTO.SelectedValue))
                    {
                        Session["Distance"] = objHuyen.Kms;
                        LocationInfo += " : " + objHuyen.Kms + " km";
                    }
                    Session["LocationInfo"] = LocationInfo;
                }
            }
        }
        if (int.Parse(Session["TruckerPriceExID"].ToString()) == 0)
        {
            Session["LocationInfo"] = "";
            lblerror.Text = "Ex không đúng.";
            return;
        }
        Response.Redirect("TruckerPrice.aspx");
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        TruckerPrice obj = new TruckerPrice();
        obj.ID = -1;
        string sqlCommand = "";
        sqlCommand = "select ID from tbl_Trucker WHERE LocationID=" + Session["TruckerPriceToID"].ToString() + " order by BizName";
        DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            obj.TruckerID = long.Parse(dr["ID"].ToString());
            obj.ExID = long.Parse(Session["TruckerPriceExID"].ToString());
            obj.ToID = long.Parse(Session["TruckerPriceToID"].ToString());

            obj.Save(GV.cn, GV.trans);
        }
        Response.Redirect("TruckerPrice.aspx");
    }
    protected void LoadDropDownTo()
    {
        string sqlCommand = "Select ID,Name From tbl_Location where 1=1";
        //if (nPermissions < 9)
        //    sqlCommand += " AND ID in(" + Session["UserLocationIDs"].ToString() + ")";
        DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        ddTO.DataSource = dt;
        ddTO.DataTextField = dt.Columns[1].ToString();
        ddTO.DataValueField = dt.Columns[0].ToString();
        ddTO.DataBind();

        if (Session["TruckerPriceToID"] != null)
        {
            if (ddTO.Items.FindByValue(Session["TruckerPriceToID"].ToString()) != null)
                ddTO.SelectedValue = Session["TruckerPriceToID"].ToString();
        }
    }

}
